package models

import (
	"math/rand"
	"my-yipuku/db"
	"strconv"
	"time"
)

type UserOrder struct {
	ID          string  `json:"id"`
	OrderId     string  `json:"order_id"`
	UserId      int     `json:"user_id"`
	Source      int     `json:"source"`
	ProductType int     `json:"product_type"`
	Money       float64 `json:"money"`
	Title       string  `json:"title"`
	desc        string  `json:"desc"`
	PayStatus   int     `json:"pay_status"`
	PayAt       int     `json:"pay_at"`
	CreatedAt   int     `json:"created_at"`
	UpdatedAt   int     `json:"updated_at"`
}

/*
 * 生成订单ID
 */
func (u UserOrder) CreatedId() string {
	rand.Seed(time.Now().UnixNano())
	timeNum := time.Now().Format("20060102")
	randNum := rand.Intn(1000000)
	id := timeNum + strconv.Itoa(randNum)
	return id
}

/**
 * 创建用户订单
 * @param userId int 用户ID
 * @param money float 订单金额
 * @param source int 订单来源
 * @param productType int 订单类型
 * @param title string 订单标题
 * @param desc string 订单描述
 * @return string 订单ID
 */
func (u UserOrder) CreatedOrder(userId int, money float64, source int, productType int, title, desc string) string {
	// 生成ID
	id := u.CreatedId()
	order := UserOrder{
		ID:          id,
		UserId:      userId,
		Money:       money,
		Source:      source,
		ProductType: productType,
		Title:       title,
		desc:        desc,
		PayStatus:   0,
		PayAt:       0,
		CreatedAt:   0,
		UpdatedAt:   0,
	}
	db.Db.Create(&order)
	if db.Db.Error != nil {
		return ""
	} else {
		return ""
	}
}

// 查询用户已购买的曲谱
func (u UserOrder) GetList(userId, page int, limit int) []UserOrder {
	var list []UserOrder
	db.Db.Where("user_id = ? and status = 1 and pay_status = 1", userId).Offset((page - 1) * limit).Limit(limit).Order("created_at desc").Find(&list)
	return list
}
